<template>
  <SelectBlock @click="showDate = true" :text="showName" />
  <van-popup v-model:show="showDate" round position="bottom" :teleport="body">
    <van-date-picker v-model="date" @cancel="showDate = false" @confirm="onConfirm"
      :columns-type="['year', 'month', 'day']" :formatter="formatter" :max-date="maxDate" />
  </van-popup>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import SelectBlock from '../basic-components/SelectBlock.vue'

const props = defineProps(['modelValue'])
const emits = defineEmits(['update:modelValue', 'confirm'])

const maxDate = ref(null)
const body = document.body
const showDate = ref(false)
const date = ref(['', '', '']) // [year, month, day]

const today = new Date()
const currentYear = today.getFullYear().toString()
const currentMonth = ('0' + (today.getMonth() + 1)).slice(-2)
const currentDay = ('0' + today.getDate()).slice(-2)
const showName = ref(`${currentYear}年${currentMonth}月${currentDay}日`)

const onConfirm = (value) => {
  const [year, month, day] = value.selectedValues
  const formattedMonth = ('0' + month).slice(-2)
  const formattedDay = ('0' + day).slice(-2)
  const displayText = `${year}年${formattedMonth}月${formattedDay}日`

  showName.value = displayText
  showDate.value = false

  const modelValue = [year, formattedMonth, formattedDay];
  emits('update:modelValue', modelValue)
  emits('confirm', modelValue)
}

const formatter = (type, option) => {
  if (type === 'year') option.text += '年'
  if (type === 'month') option.text += '月'
  if (type === 'day') option.text += '日'
  return option
}

onMounted(() => {
  maxDate.value = new Date()

  if (props.modelValue && props.modelValue.length == 3) {
    const [year, month, day] = props.modelValue
    date.value = [year, ('0' + parseInt(month)).slice(-2), ('0' + parseInt(day)).slice(-2)]
    showName.value = `${year}年${date.value[1]}月${date.value[2]}日`
  } else {
    date.value = [currentYear, currentMonth, currentDay]
    showName.value = `${currentYear}年${currentMonth}月${currentDay}日`
    emits('update:modelValue', date.value)
    emits('confirm', date.value)
  }
})

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && newVal.length == 3) {
      const [year, month, day] = newVal
      date.value = [year, ('0' + parseInt(month)).slice(-2), ('0' + parseInt(day)).slice(-2)]
      showName.value = `${year}年${date.value[1]}月${date.value[2]}日`
    } else {
      date.value = [currentYear, currentMonth, currentDay]
      showName.value = `${currentYear}年${currentMonth}月${currentDay}日`
    }
  }
)
</script>

<style lang="scss" scoped></style>